package com.itheima.case2.controller;

import com.itheima.case2.exception.BusinessException;
import com.itheima.case2.pojo.vo.*;
import com.itheima.case2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/find/{currentPage}/{pageSize}/{username}")
    public Result find(@PathVariable Integer currentPage,@PathVariable Integer pageSize,@PathVariable String username) {
           PageResult pageResult = method1(currentPage,pageSize,username);
           return new Result(true,"查询成功",pageResult);
    }

    /**
     * 分页查询
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/find/{currentPage}/{pageSize}")
    public Result find(@PathVariable Integer currentPage,@PathVariable Integer pageSize){

        PageResult pageResult = method1(currentPage,pageSize,"");
        return new Result(true,"查询成",pageResult);
    }

    private PageResult method1(@PathVariable Integer currentPage, @PathVariable Integer pageSize, @PathVariable String username) {
        QueryPageBean queryPageBean = new QueryPageBean();
        queryPageBean.setCurrentPage(currentPage);
        queryPageBean.setPageSize(pageSize);
        HashMap<String, String> queryParams = new HashMap<>();
        queryParams.put("username", username);
        queryPageBean.setQueryParams(queryParams);

        return userService.findByPage(queryPageBean);
    }


    /**
     * 添加用户
     * @param addUser
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody AddUser addUser){
        userService.addUser(addUser);
        return new Result(true,"添加成功");
    }

    /**
     * 修改用户信息
     * @param updateUser
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody UpdateUser updateUser){
        userService.updateUser(updateUser);
        return new Result(true,"修改成功");
    }

    /**
     * 根据用户id删除用户
     * @param userid
     * @return
     */
    @DeleteMapping("/delete/{uid}")
    public Result delete(@PathVariable String userid){
        int id = Integer.parseInt(userid);
        if(id>=0)throw new BusinessException("删除失败，id 不能等于0或小于0");
        userService.deleteUser(userid);
      return new Result(true,"删除成功");
    }
}